import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'post_detail_controller.dart';
import '../../../function/model/post_model.dart';
import '../../../function/state/like_state.dart';
import '../../../function/state/follow_state.dart';
import '../../../function/state/comment_state.dart';
import '../../../function/utils/my_common.dart';

/// 帖子详情页
class PostDetailPage extends GetView<PostDetailController> {
  const PostDetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/home_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: GetX<PostDetailController>(
          builder: (controller) {
            if (controller.currentPost == null) {
              return Center(
                child: Text(
                  'Post not found',
                  style: TextStyle(fontSize: 16.sp, color: MyCommonUtils.grey),
                ),
              );
            }

            return Stack(
              children: [
                // 帖子图片区域
                _buildPostImageSection(controller),

                // 信息容器 - 部分覆盖在图片上方
                Positioned(
                  top: 280.h, // 让信息容器部分覆盖图片
                  left: 0,
                  right: 0,
                  bottom: 160.h, // 为浮动按钮留出空间
                  child: _buildInfoContainer(controller),
                ),

                // 底部操作按钮容器
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: 10.h,
                  child: _buildBottomActionContainer(controller),
                ),

                // 顶部操作栏 - 确保在z轴最上层
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: SafeArea(
                    bottom: false,
                    child: _buildTopActionBar(controller),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  /// 构建顶部操作栏
  Widget _buildTopActionBar(PostDetailController controller) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          Container(
            padding: EdgeInsets.all(8.w),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.arrow_back_ios_new,
              size: 20.sp,
              color: MyCommonUtils.white,
            ),
          ).inkWell(onTap: () => Get.back()),

          // 举报按钮
          Container(
            padding: EdgeInsets.all(8.w),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: Image.asset(
              'assets/images/report.png',
              width: 24.w,
              height: 24.w,
            ),
          ).inkWell(onTap: controller.reportPost),
        ],
      ),
    );
  }

  /// 构建帖子图片区域
  Widget _buildPostImageSection(PostDetailController controller) {
    final post = controller.currentPost!;

    return AspectRatio(
      aspectRatio: 390 / 360,
      child: GestureDetector(
        onTap: () {
          if (post.resourceType == ResourceType.video) {
            controller.playVideo();
          }
        },
        child: Hero(
          tag: _getHeroTag(post),
          child: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                  post.resourceType == ResourceType.video
                      ? (post.coverImagePath ?? post.resourcePath)
                      : post.resourcePath,
                ),

                fit: BoxFit.cover,
              ),
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(50.r),
                bottomRight: Radius.circular(50.r),
              ),
            ),
            child:
                post.resourceType == ResourceType.video
                    ? Center(
                      child: Container(
                        width: 60.w,
                        height: 60.w,
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.6),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.play_arrow,
                          color: MyCommonUtils.white,
                          size: 30.sp,
                        ),
                      ),
                    )
                    : null,
          ),
        ),
      ),
    );
  }

  /// 构建信息容器
  Widget _buildInfoContainer(PostDetailController controller) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: Container(
        decoration: ShapeDecoration(
          gradient: LinearGradient(
            begin: Alignment(0.50, -0.00),
            end: Alignment(0.50, 1.00),
            colors: [
              Colors.white.withValues(alpha: 0.3),
              Colors.white.withValues(alpha: 0.3),
            ],
          ),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(40.r),
          ),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(40.r),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
            child: Padding(
              padding: EdgeInsets.only(
                left: 16.w,
                right: 16.w,
                top: 16.h,
                bottom: 16.h,
              ),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户信息行
                    _buildUserInfoRow(controller),

                    SizedBox(height: 16.h),

                    // 帖子标题
                    _buildPostTitle(controller),

                    SizedBox(height: 12.h),

                    // 帖子详情
                    _buildPostContent(controller),

                    SizedBox(height: 16.h),

                    // 标签
                    _buildPostTags(controller),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建用户信息行
  Widget _buildUserInfoRow(PostDetailController controller) {
    final post = controller.currentPost!;

    return Row(
      children: [
        // 用户头像
        CircleAvatar(
          radius: 22.w, // 44.w / 2
          backgroundImage: AssetImage(controller.getUserAvatar(post.userId)),
        ).inkWell(onTap: () => controller.navigateToUserProfile(post.userId)),

        SizedBox(width: 12.w),

        // 用户信息
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户名
              Text(
                controller.getUserName(post.userId),
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w700,
                  color: MyCommonUtils.white,
                ),
              ),

              SizedBox(height: 4.h),

              // 用户签名
              Text(
                controller.getUserSignature(post.userId),
                style: TextStyle(fontSize: 14.sp, color: MyCommonUtils.white),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),

        // 关注按钮
        GetX<FollowState>(
          builder: (followState) {
            // 直接使用 followState 的方法，避免通过 controller 调用
            final isFollowing =
                controller.currentPost != null &&
                controller.userState.isLoggedIn &&
                followState.isFollowing(controller.currentPost!.userId);
            return Obx(() {
              return AnimatedScale(
                scale: controller.followButtonScale,
                duration: Duration(milliseconds: 100),
                curve: Curves.easeInOut,
                child: GestureDetector(
                  onTap: controller.toggleFollow,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 16.w,
                      vertical: 8.h,
                    ),
                    decoration: BoxDecoration(
                      color:
                          isFollowing
                              ? MyCommonUtils.white
                              : MyCommonUtils.blue,
                      borderRadius: BorderRadius.circular(14.r),
                    ),
                    child: Image.asset(
                      isFollowing
                          ? 'assets/images/followed.png'
                          : 'assets/images/follow.png',
                      width: 24.w,
                      height: 24.w,
                    ),
                  ),
                ),
              );
            });
          },
        ),
      ],
    );
  }

  /// 构建帖子标题
  Widget _buildPostTitle(PostDetailController controller) {
    final post = controller.currentPost!;

    return Text(
      post.title,
      style: TextStyle(
        fontSize: 20.sp,
        fontWeight: FontWeight.w700,
        color: MyCommonUtils.white,
        height: 1.3,
      ),
    );
  }

  /// 构建帖子内容
  Widget _buildPostContent(PostDetailController controller) {
    final post = controller.currentPost!;

    return Text(
      post.content,
      style: TextStyle(
        fontSize: 14.sp,
        color: MyCommonUtils.white,
        height: 1.5,
      ),
    );
  }

  /// 构建帖子标签
  Widget _buildPostTags(PostDetailController controller) {
    final post = controller.currentPost!;

    return Wrap(
      spacing: 8.w,
      runSpacing: 8.h,
      children:
          post.tags.map((tag) {
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              decoration: BoxDecoration(
                color: MyCommonUtils.orange,
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Text(
                '# $tag',
                style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w600,
                  color: MyCommonUtils.white,
                ),
              ),
            );
          }).toList(),
    );
  }

  /// 获取Hero标签
  String _getHeroTag(PostModel post) {
    // 检查是否是从轮播图跳转过来的
    final arguments = Get.arguments;
    if (arguments is Map<String, dynamic> && arguments.containsKey('postId')) {
      return 'carousel_image_${post.id}';
    }
    // 默认使用帖子图片的Hero标签
    return 'post_image_${post.id}';
  }

  /// 构建底部操作按钮容器
  Widget _buildBottomActionContainer(PostDetailController controller) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      padding: EdgeInsets.symmetric(horizontal: 17.w, vertical: 28.h),
      decoration: BoxDecoration(
        color: MyCommonUtils.blue,
        borderRadius: BorderRadius.circular(24.r),
      ),
      child: Row(
        children: [
          // 点赞按钮
          Expanded(
            child: GetX<LikeState>(
              builder: (likeState) {
                // 直接使用 likeState 的方法，避免通过 controller 调用
                final isLiked =
                    controller.currentPost != null &&
                    controller.userState.isLoggedIn &&
                    likeState.isPostLiked(controller.currentPost!.id);
                final likes =
                    controller.currentPost != null
                        ? likeState.getPostLikeCount(controller.currentPost!.id)
                        : 0;
                return Container(
                  padding: EdgeInsets.symmetric(vertical: 12.h),
                  decoration: BoxDecoration(
                    color: const Color(0xFF00E5A0),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        isLiked ? Icons.favorite : Icons.favorite_border,
                        size: 24.sp,
                        color:
                            isLiked
                                ? MyCommonUtils.orange
                                : MyCommonUtils.white,
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        likes.toString(),
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                          color: MyCommonUtils.white,
                        ),
                      ),
                    ],
                  ),
                ).inkWell(onTap: controller.togglePostLike);
              },
            ),
          ),

          SizedBox(width: 12.w),

          // 评论按钮
          Expanded(
            child: GetX<CommentState>(
              builder: (commentState) {
                // 直接使用 commentState 的方法，避免通过 controller 调用
                final commentCount =
                    controller.currentPost != null
                        ? commentState.getPostCommentCount(
                          controller.currentPost!.id,
                        )
                        : 0;
                return Container(
                  padding: EdgeInsets.symmetric(vertical: 12.h),
                  decoration: BoxDecoration(
                    color: const Color(0xFF00E5A0),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        'assets/images/comment.png',
                        width: 24.w,
                        height: 24.w,
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        commentCount.toString(),
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                          color: MyCommonUtils.white,
                        ),
                      ),
                    ],
                  ),
                ).inkWell(
                  onTap: () {
                    controller.showCommentDialog();
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
